from flask import Flask
from flask_restful import Api
from flask_sqlalchemy import SQLAlchemy
from flask_cors import CORS
from flask_redis import FlaskRedis
from flask_limiter import Limiter
from utils.send_email import BaseMail

redis_store = FlaskRedis()
app = Flask(__name__)
mail = BaseMail(app)
db = SQLAlchemy()
from utils.authenticate import get_token

# flask 节流 参数
limiter = Limiter(
    app,
    key_func=get_token,
)
from config import app_config
from apis.users import User, Login, LoginOut
from apis.project import ProjectList,ProjectAdd,ProjectUpdate,ProjectDelete
from apis.hostsmanager import HostAdd,HostEdit,HostDel,HostList
from apis.case_suite import CaseSuiteList,CaseSuiteAdd,CaseSuiteUpdate



def create_app(config_name='test'):
    app.config.from_object(app_config[config_name])
    api = Api(app)
    db.init_app(app)
    mail.init_app(app)
    redis_store.init_app(app)
    api.add_resource(User, '/user/adduser')
    api.add_resource(Login, '/user/login')
    api.add_resource(LoginOut, '/user/loginout')
    api.add_resource(ProjectList, '/project/list')
    api.add_resource(ProjectAdd,'/project/add')
    api.add_resource(ProjectUpdate,'/project/update')
    api.add_resource(ProjectDelete,'/project/delete')
    api.add_resource(CaseSuiteList,'/casesuite/list')
    api.add_resource(CaseSuiteAdd,'/casesuite/add')
    api.add_resource(CaseSuiteUpdate,'/casesuite/update')
    api.add_resource(HostAdd, '/host/addhost')
    api.add_resource(HostEdit, '/host/edithost')
    api.add_resource(HostDel, '/host/delhost')
    api.add_resource(HostList, '/host/hostlist')
    CORS(app, supports_credentials=True, resources={r"/*": {"origins": "*"}})
    return app
